/**
 * Created by 83617 on 2019/1/11.
 */
var User = require('../models/user')

//adminLogin
exports.toLoginPage = function(req,res){
    res.render('adminLogin',{})
}

//to register
exports.register = function(req,res){
    //console.log(req.body.username)
    var username = req.body.username
    var password = req.body.password
    User.findByName(username,function(err,user){
        if(err) console.log(err)
        if(user){
            res.json({errMessage:'该用户已存在！'})
        }else{
            var user = new User({
                username:username,
                password:password
            })
            user.save(function(err,user){
                if(err) console.log(err)
                res.json({message:'注册成功！！'})
                //res.redirect('/adminLogin')
            })
        }
    })
}

//to Login, and checking the password
exports.login = function(req,res){
    var username = req.body.username
    var password = req.body.password
    User.findByName(username,function(err,user){
        if(err) console.log(err)
        if(!user) res.json({message:"该用户不存在！"})
        user.comparePassword(password,function(err,isMatch){
            if(err) console.log(err)
            if(isMatch){
                //console.log(isMatch)
                req.session.user = user  //标记登录状态
                res.json({isMatch:isMatch})
            }else{
                res.json({message:"密码不正确！"})
            }
        })
    })
}

//logout
exports.logout = function(req,res){
    delete req.session.user
    //delete app.locals.user
    res.redirect('/adminLogin')
}

//authority
exports.admin = function(req,res,next){
    var user = req.session.user
    if(!user){
        res.redirect('/adminLogin')
    }
    next()
}